package com.cn.music.view;

import android.util.Log;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.cn.music.model.UserDetailModel;
import com.cn.music.server.Api;
import com.cn.music.server.Constant;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @Auth: 陈彬
 * @Date: 2020/9/24 10:28
 */
public class UserDetailViewModel extends ViewModel {

    private Retrofit retrofit;
    private MutableLiveData<List<UserDetailModel>> userDetailModel;
    private final static String TAG = "UserDetailModel";

    public LiveData<List<UserDetailModel>> loadUserDetailModel(String uid) {
        if (userDetailModel == null) {
            userDetailModel = new MutableLiveData<>();
            responseUserDetailModel(uid);
        }
        return userDetailModel;
    }

    private void responseUserDetailModel(String uid) {
        retrofit = new Retrofit.Builder()
                .baseUrl(Constant.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        Api api = retrofit.create(Api.class);
        Call<UserDetailModel> call = api.getUserDetail(uid);
        call.enqueue(new Callback<UserDetailModel>() {
            @Override
            public void onResponse(Call<UserDetailModel> call, Response<UserDetailModel> response) {
                UserDetailModel model = response.body();
                List<UserDetailModel> models = new ArrayList<>();
                models.add(model);
                userDetailModel.setValue(models);
            }

            @Override
            public void onFailure(Call<UserDetailModel> call, Throwable t) {
                Log.e(TAG,"请求错误信息:"+ t.getMessage());
            }
        });
    }

}
